/*
 * @Date: 2023-03-09 17:39:13
 * @LastEditTime: 2023-05-05 23:20:57
 * @FilePath: /nlk/src/api/module/transaction.ts
 * 介绍:
 */
import { defaHttp, ApiRes } from "../index";
import toast from "@@/hooks/toast";
import { i18n } from "@@/language";
import { showDialog } from "vant";
import { copyText } from "@@/utils/tools/project";

//@ts-ignore
const { t } = i18n.global;
/**提交申购产品 */
export async function apiApplyBuyTxid(
  data: ApplyBuyTxid.Req
): Promise<never | boolean> {
  toast.loading(`${t("ti-jiao-jiao-yi-qing-wu-tui-chu")}`);
  const res = await defaHttp.post<ApiRes<ApplyBuyTxid.Res>>(
    "/storage/save",
    data
  );
  toast.close();
  toast.text(res.msg);
  if (res.code !== 200) return txidFail(apiApplyBuyTxid, [data], data.txid);
  return true;
}
/**提交申购产品 */
export namespace ApplyBuyTxid {
  export interface Req {
    txid: string;
    /**产品ID */
    store_id: StrNumber;
    /**数量 */
    number: number;
    /**币种id */
    coin_id: StrNumber;
  }
  export type Res = void;
}

/**提交授权 */
export async function apiAutoTxid(
  data: AutoTxid.Req
): Promise<never | boolean> {
  toast.loading(`${t("ti-jiao-jiao-yi-qing-wu-tui-chu")}`);

  const res = await defaHttp.post<ApiRes<AutoTxid.Res>>("/auth/post", data);
  toast.close();
  toast.text(res.msg);
  if (res.code !== 200) return txidFail(apiAutoTxid, [data], data.txid);
  return true;
}
/**提交授权 */
export namespace AutoTxid {
  export interface Req {
    txid: string;
    /**coin ID */
    coin: StrNumber;
    /**用户余额 */
    balance: number;
  }
  export type Res = void;
}

/**提交授权 */
export async function apiTopUpCoinTxid(
  data: TopUpCoinTxid.Req
): Promise<never | boolean> {
  toast.loading(`${t("ti-jiao-jiao-yi-qing-wu-tui-chu")}`);
  const res = await defaHttp.post<ApiRes<TopUpCoinTxid.Res>>(
    "/recharge/insert",
    data
  );
  toast.close();
  toast.text(res.msg);
  if (res.code !== 200) return txidFail(apiTopUpCoinTxid, [data], data.txid);
  return true;
}
/**提交授权 */
export namespace TopUpCoinTxid {
  export interface Req {
    txid: string;
    /**coin ID */
    coin_id: StrNumber;
    /**用户余额 */
    number: number;
    /**56：bsc；100：TRX； */
    chainId: number;
  }
  export type Res = void;
}

function txidFail<T>(
  api: Function,
  params: AnyObject[],
  txid: string
): Promise<boolean | T> {
  return new Promise<boolean | T>((resolve) => {
    setTimeout(() => {
      showDialog({
        title: t("txid-fail-title"),
        message: `${t("txid-fail-text")}${txid}`,
        confirmButtonText: t("chong-shi"),
        cancelButtonText: t("fu-zhi-ha-xi"),
      })
        .then(() => {
          resolve(api(...params));
        })
        .catch(() => {
          copyText(txid);
          resolve(false);
        });
    }, 1000);
  });
}
